//
//  PKRequestManager.m
//  PianKe
//
//  Created by Li on 15/7/21.
//  Copyright (c) 2015年 Li. All rights reserved.
//

#import "LJRequestManagerBlock.h"

@interface LJRequestManagerBlock ()<NSURLConnectionDataDelegate>

@property (nonatomic, strong) NSMutableData *data;

@end

@implementation LJRequestManagerBlock

+ (void)manager:(RequestType)requestType requestWith:(NSString *)urlStr dic:(NSDictionary *)dic finish:(RequestFinish)finish error:(RequestError)error{
    LJRequestManagerBlock *manager = [[LJRequestManagerBlock alloc] init];
    [manager manager:requestType requestWith:urlStr dic:dic finish:finish error:error];
}

- (void)manager:(RequestType)requestType requestWith:(NSString *)urlStr dic:(NSDictionary *)dic finish:(RequestFinish)finish error:(RequestError)error{
    self.requestFinish = finish;
    self.requestError = error;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    if (requestType == POST) {
        [request setHTTPMethod:@"POST"];
        if (dic) {
            [request setHTTPBody:[self dicToHTTPBody:dic]];
        }
    }
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    _data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    self.requestFinish(_data);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    self.requestError(error);
}

- (NSData *)dicToHTTPBody:(NSDictionary *)dic{

    NSData *data = [self toJSONData:dic];
    return data;
    
}

- (NSData *)toJSONData:(id)theData{
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        return jsonData;
    }
    else{
        return nil;
    }
}
@end
